/*
 * Table.java
 *
 * Created on May 4, 2006, 10:29 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 *
 *    Apr, 6, 2011. Relabeled as astract.
 */
package portfolio.dbHost.dataBases.dbTable;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import portfolio.dbHost.dataBases.dbTable.tblColumn.Column;
import misellanea.MiscellaneaDB;
import portfolio.configMessage.configMessageEvent;
import portfolio.configMessage.configMessageFrame;
import portfolio.configMessage.configMessageListener;
    import portfolio.dbHost.dataBases.DBase;
import portfolio.mainScreen;

/**
 *
 * @author ACA
 */

public abstract class Table implements configMessageListener, MouseListener
{
    private mainScreen         mainFrame = null;
    private DBase              dBase     = null;
    private configMessageFrame msgFrame  = null;        
    
    protected String         sDBName      = null;
    protected String         sTableName   = null;
    protected Vector         vColumns     = null;
    protected int            iColumnCount = 0;
    protected Column[]       columns      = null;
    protected Connection     connection   = null;
    
    private JTree          dbaseTree    = null;    
    
    private final String   MSG_IMPROPER_COLUMNCTR            = "improper column counter";
    private final String   ACTION_DB_TAB_DROP_TABLE          = "Drop table";
    private final String   ACTION_DB_TAB_CREATE_COLUMN       = "Create column";
    
    private final String   ACTION_NEW_PROJECT_EXCLUDE_TABLE  = "Exclude table";
    private boolean bExcludeTable = false;
    /**
     *
     * @param e 
     */
    public void okSelected(configMessageEvent e) 
    {
        try {
            //String sTableName = msgFrame.getFieldName();
            String sCommand = msgFrame.getSQLStatementMnemonic();
            if        (sCommand.equals(this.ACTION_DB_TAB_DROP_TABLE)) {
                this.drop();
                mainFrame.displayMessage("Table.okSelected 67", "Drop table " + sTableName + " successful.");
            } else if (sCommand.equals(this.ACTION_DB_TAB_CREATE_COLUMN)) {
                String sColumnName = msgFrame.getFieldName();
                if (sColumnName != null) { 
 //                   this.createColumn(sColumnName);
                    Column.create (connection, sTableName, sColumnName);
                    mainFrame.displayMessage("Table.okSelected 72", "Create column " + sColumnName + " successful.");
                } else {
                    mainFrame.displayMessage("Table.okSelected 64", "Null column name.");
                }
                //System.out.println ("\t\t\tCreate column: ");//sCommand);
            }
            dBase.getDBHost().buildDBTree();
            dBase.getDBHost().updateDBTree(); //mainFrame.getDBasePanel());

            msgFrame.dispose();
        } catch (Exception ex) {
            mainFrame.displayMessage("Table.okSelected 84", ex.getMessage());
        }
    }
    /**
     *
     * @param e 
     */
    public void cancelSelected(configMessageEvent e) 
    {
        msgFrame.dispose();
    }
    /**
     * Mouse listener abstract members:
     *  mouseClicked, mousePressed, mouseReleased, mouseEntred.
     */
    int mouseReleased = 1;
    public void mouseClicked(MouseEvent arg0) {
        String sClassName = arg0.getClass().getName();
        System.out.println (mouseReleased++ + " className: " + sClassName  + ": Table: {{{{{{{{{{{{{{{{{{{{{{{{{ Mouse Clicked }}}}}}}}}}}}}}}}}}}}}}}}}");
    }
    public void mousePressed(MouseEvent arg0) {
        String sClassName = arg0.getClass().getName();
        System.out.println (mouseReleased++ + " className: " + sClassName  + ": Table: {{{{{{{{{{{{{{{{{{{{{{{{{ Mouse Pressed }}}}}}}}}}}}}}}}}}}}}}}}}");
        Object o = arg0.getSource();
        JMenuItem jTempMenuItem = (JMenuItem) o;

        try {
            String sCommand = jTempMenuItem.getActionCommand();
            if (sCommand.equals (this.ACTION_DB_TAB_DROP_TABLE)) {
                msgFrame = new configMessageFrame (mainFrame, this.sTableName,
                                                   this.ACTION_DB_TAB_DROP_TABLE, 250, 120);
                msgFrame.showMessageFrame();
                msgFrame.addConfigMessageListener(this);
            } else if (sCommand.equals(this.ACTION_DB_TAB_CREATE_COLUMN)) {
                msgFrame = new configMessageFrame (mainFrame, this.ACTION_DB_TAB_CREATE_COLUMN, 250, 120);
                msgFrame.showMessageFrame();
                msgFrame.addConfigMessageListener(this);
            } else if (sCommand.equals (ACTION_NEW_PROJECT_EXCLUDE_TABLE)) {
                bExcludeTable = true;
            }
        } catch (Exception ex) {
            mainFrame.displayMessage("Table.mousePressed 126", ex.getMessage());
        }
    }

    public void mouseReleased(MouseEvent arg0) {
        String sClassName = arg0.getClass().getName();
        System.out.println (mouseReleased++ + " className: " + sClassName  + ": Table: {{{{{{{{{{{{{{{{{{{{{{{{{ Mouse Released }}}}}}}}}}}}}}}}}}}}}}}}}");
    }

    public void mouseEntered(MouseEvent arg0) {
        String sClassName = arg0.getClass().getName();
        System.out.println (mouseReleased++ + " className: " + sClassName  + ": Table: {{{{{{{{{{{{{{{{{{{{{{{{{ Mouse Entered }}}}}}}}}}}}}}}}}}}}}}}}}");
    }

    public void mouseExited(MouseEvent arg0) {
        String sClassName = arg0.getClass().getName();
        System.out.println (mouseReleased++ + " className: " + sClassName  + ": Table: {{{{{{{{{{{{{{{{{{{{{{{{{ Mouse Exited }}}}}}}}}}}}}}}}}}}}}}}}}");
    }
    /**
     * Given that the table already exists, maybe with columns, creates a new instance of Table.
     * 
     * @param dBaseParam 
     * @throws java.lang.Exception 
     * @throws java.sql.SQLException 
     * @param sTableParam 
     */
    public Table(DBase dBaseParam, String sTableParam) throws Exception, SQLException 
    {
        dBase = dBaseParam;
        if (dBase == null)
            throw new Exception ("null dBase parameter.");
        mainFrame = dBase.getDBHost().getMainScreen();
        if (mainFrame == null)
            throw new Exception ("null mainFrame parameter.");   
        connection = dBase.getDBHost().getConnection();
        if (connection == null)
            throw new Exception ("null connection.");
        
        sDBName = dBase.getDBName();
        this.setName (sTableParam);
        this.buildColumns();
    } /* end constructor Table */    
    public Table(DBase dBaseParam) throws Exception 
    {
        dBase = dBaseParam;
        if (dBase == null)
            throw new Exception ("null dBase parameter.");
        mainFrame = dBase.getDBHost().getMainScreen();
        if (mainFrame == null)
            throw new Exception ("null mainFrame parameter.");   
        connection = dBase.getDBHost().getConnection();
        if (connection == null)
            throw new Exception ("null connection.");
        
        sDBName = dBase.getDBName();
    }
    /**
     * 
     * @param sTableNameParam 
     */
    public void setName (String sTableNameParam) throws Exception
    {
        if (sTableNameParam == null)
            throw new Exception ("Error null TableName.");
        if (sTableNameParam.length() <= 0)
            throw new Exception ("TableName lrngth <= 0.");
        
        sTableName = sTableNameParam;
        return;
    }
    /**
     *
     *
     */
    abstract public Vector [] describeAll (Connection connectParam, String sDBNameParam, String sTable) throws Exception;

    /**
     * This method is part of the class contriction sequence and was created for the need to have a short constructor
     * that doesn't takes sTableName as argument; so, in order to create the Table class using the short constructor, use
     *  new Table (dBaseParam);
     *  setTableName (sTableName);
     *  buildColimns ();
     *  sequence in order to create the full table object.
     */
    abstract public void buildColumns () throws Exception, SQLException;
    /**
     *
     * @return 
     */
    public String getTableName ()
    {
        return sTableName;
    }
    /**
     *
     * @return 
     */
    public Vector describeTable ()
    {
        return vColumns;
    }
    /**
     *
     * @param iIdx 
     * @return 
     * @throws java.lang.Exception 
     */
    public String getColumnName (int iIdx) throws Exception
    {
        if (iIdx < 0 || iIdx > iColumnCount)
            throw new Exception (MSG_IMPROPER_COLUMNCTR);
        
        return (String) vColumns.get(iIdx);
    }
    /**
     *
     * @return 
     */
    public int getColumnCount ()
    {
        return iColumnCount;
    }
    /**
     *
     * @param iIdx 
     * @return 
     * @throws java.lang.Exception 
     */
    public Column getColumnDescription (int iIdx) throws Exception
    {
        if (iIdx < 0 || iIdx > iColumnCount)
            throw new Exception (MSG_IMPROPER_COLUMNCTR);
        
        return columns [iIdx];
    }
    /**
     *
     * @param sColumnParam 
     * @return 
     */
    public Column getColumnDescription (String sColumnParam)
    {
        if (!vColumns.contains (sColumnParam))
            return null;
        
        int iColumnIndex = vColumns.indexOf(sColumnParam);
        
        return columns [iColumnIndex];
    }
    /**
     *
     * @param sColumnParam 
     * @return 
     */
    public Column getColumnDescriptionIgnoreCase (String sColumnParam)
    {
        if (sColumnParam == null)
            return null;
        
        int iSize = vColumns.size();
        for (int iIdx = 0; iIdx < iSize; iIdx++) {
            if (vColumns.get(iIdx).toString().equalsIgnoreCase(sColumnParam)) {
                return columns [iIdx];
            }
        }
        
        return null;
    }    
    /**
     *
     * @return 
     * @throws java.lang.Exception
     *
     * 0j0: this method is dependent of hard coded column names.
     */
    public Vector [] selectAllfromTable () throws Exception
    {
        Vector [] outVector = null;
        try {
            Statement statement = connection.createStatement ();
            statement.execute ("USE " + sDBName + ";");

            ResultSet resultSet = statement.executeQuery ("SELECT * FROM " + sTableName + " ;");
            if (!resultSet.next ()) {
                throw new Exception (" resultSet = null");
            }
            ResultSetMetaData rsmd = resultSet.getMetaData ();

            int iColumnCount = rsmd.getColumnCount();
          
            if (iColumnCount == 0) {
                throw new Exception ("null iColumnCount.");
            }
            outVector = new Vector [iColumnCount];
            for (int iIdx = 0; iIdx < iColumnCount; iIdx++) {
                outVector [iIdx] = new Vector ();
            }
            
            do {
                for (int iIdx = 1; iIdx <= iColumnCount; iIdx++) {
                    String resultString = resultSet.getString(iIdx);
                    if (columns [iIdx -1].getType().equals(Column.COLUMN_DATE)) {
                        resultString = "'" + resultString + "'";
                    }
                    if (columns [iIdx -1].getType().equals(Column.COLUMN_TIME)) { //0j0 not tested
                        resultString = "'" + resultString + "'";      //0j0
                    }                                                 //0j0
                    outVector [iIdx -1].addElement(resultString);
                }
            } while (resultSet.next ());
        }
        catch (SQLException sqlex) {
            throw new Exception (sqlex);
        }
        return outVector;
    } /* end method selectAllFromTable */
    /**
     *
     * @return 
     */
    public DefaultMutableTreeNode processTreeHierarchy ( ) 
    {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode (sTableName);
        DefaultMutableTreeNode child = null;
        
        for (int i = 0; i < columns.length; i++) {
            child = columns [i].processTreeHierarchy();
            node.add (child);
        }
        return (node);
    } /* end method processHierarchy */
    /**
     *
     * @return 
     * @throws java.lang.Exception 
     */
//    public DefaultMutableTreeNode processPrjHierarchy ( ) throws Exception 
//    {
//        DefaultMutableTreeNode node = new DefaultMutableTreeNode (sTableName);
//        DefaultMutableTreeNode [] nodeColumns = new DefaultMutableTreeNode [iColumnCount]; 
//        DefaultMutableTreeNode nodeAttrib  [] = null;
//        
//        for (int iCols = 0; iCols < iColumnCount; iCols++) {
//            String sColumn = columns [iCols].getField();
//            nodeColumns [iCols]  = new DefaultMutableTreeNode (sColumn);
//            nodeAttrib = columns [iCols].processPrjHierarchy();
//            int iNodeAttrib = nodeAttrib.length;
//            for (int iNodes = 0; iNodes < iNodeAttrib; iNodes++) {                
//                nodeColumns [iCols].add(nodeAttrib [iNodes]);
//            }
//            node.add (nodeColumns [iCols]);
//            //System.out.println("<<<<<<<<<<< " + sColumn + ">>>>>>>>>>>");
//        }
//        return (node);
//    } /* end method processHierarchy */    
    /**
     *
     * @param dbTreeParam 
     * @param iXPos 
     * @param iYPos 
     */
    public void getPopupOptions (JTree dbTreeParam, int iXPos, int iYPos)
    {
        dbaseTree = dbTreeParam;       

        JPopupMenu treeOptionsMenu = new JPopupMenu ("Options");
        dbaseTree.add(treeOptionsMenu);

        JMenuItem jItem1 = new JMenuItem (this.ACTION_DB_TAB_DROP_TABLE);
        jItem1.addMouseListener (this);
        treeOptionsMenu.add (jItem1); 
        JMenuItem jItem2 = new JMenuItem (this.ACTION_DB_TAB_CREATE_COLUMN);
        jItem2.addMouseListener (this);
        treeOptionsMenu.add (jItem2); 
        
        treeOptionsMenu.setLocation (iXPos, iYPos);
        treeOptionsMenu.show (treeOptionsMenu, iXPos, iYPos);
        
        return;
    } /* end method getPopupOptions */      
    /**
     *
     * @param oPathParam 
     * @return 
     */
    public Object getTreeObject (Object [] oPathParam)
    {
        if (oPathParam == null) {
            //error, no path param
        }
        if (oPathParam.length < 3) {
            return null;
        }
        if (!oPathParam [2].toString().equals(sTableName)) {
            //error, no database found
        }
        if (oPathParam.length != 3) {
            String sColumn = oPathParam [3].toString();
            int iIdx = vColumns.indexOf(sColumn);
            if (iIdx != -1) {
                return columns[iIdx].getTreeObject (oPathParam);
            } else {
                //error, no database found
            }
        }
        return this;
    } /* end method getTreeObject */
     /**
      *
      * @return 
      */
     public DBase getDBase ()
     {
         return dBase;
     }
     /**
      *
      * @param dbTreeParam 
      * @param iXPos 
      * @param iYPos 
      */
    public void getProjectPopupOptions (JTree dbTreeParam, int iXPos, int iYPos)
    {
        if (dbTreeParam == null) {
            mainFrame.displayMessage("Table.getProjectPopupOptions 440", "null tree.");
            return;
        }

        JPopupMenu treeOptionsMenu = new JPopupMenu ("Options");
        dbTreeParam.add(treeOptionsMenu);

        JMenuItem jExcludeItem = new JMenuItem (this.ACTION_NEW_PROJECT_EXCLUDE_TABLE);
        jExcludeItem.addMouseListener(this);
        treeOptionsMenu.add (jExcludeItem); 

        treeOptionsMenu.setLocation (iXPos, iYPos);
        treeOptionsMenu.show (treeOptionsMenu, iXPos, iYPos);
            
        return;
    } /* end method getPopupOptions */ 
    /**
     *
     * @return 
     */
    public boolean getExcludeTableFlag ()
    {
        return bExcludeTable;
    }
    /**
     *
     * @param bFlagParam 
     */
    public void setExcludeTableFlag (boolean bFlagParam)
    {
        bExcludeTable          = bFlagParam;
    }
    /**
     * 
     */
    static public void create (Connection connectionParam, String sDataBase, String sTable, String sColumnDefinition) throws Exception
    {
        if (connectionParam == null)
            throw new Exception ("No connection provided.");
        if (sDataBase == null)
            throw new Exception ("No data base name provided.");
        if (sColumnDefinition == null)
            throw new Exception ("No Column Definitions provided.");
        
        try {
            PreparedStatement pstmt = connectionParam.prepareStatement ("USE " + sDataBase);
            pstmt.execute ();
            pstmt = connectionParam.prepareStatement("CREATE TABLE " + sTable + " (" + sColumnDefinition + ");");
            pstmt.execute ();            
        } catch (SQLException sqlex) {
            throw new Exception (sqlex);
        }
        return;
    }        
    /**
     * 
     */
    public void create (String sColumnTypes) throws Exception 
    {
        Table.create (connection, sDBName, sTableName, sColumnTypes);
    }
    /********************************************************************
     * Note: try to change the name of this method in order to allow to *
     * develop another method with all the functionality  of the SQL    *
     * describe command                                                 *
     ********************************************************************/
    public static Vector describe (Connection connectParam, 
                                        String sDBNameParam, 
                                        String sTable, 
                                        String [] sExclude) throws Exception
    {
        Vector outVector = new Vector ();
        try {
            Statement statement = connectParam.createStatement ();
            statement.execute ("USE " + sDBNameParam + ";");
            ResultSet resultSet = statement.executeQuery ("DESCRIBE " + sTable + ";");
            if (!resultSet.next ()) {
                return null; //throw new Exception ("describeTable method: resultSet = null.");
            }
//            ResultSetMetaData rsmd = resultSet.getMetaData ();
            do {                
                outVector.addElement (resultSet.getString (1));
            } while (resultSet.next ());
            
            if (sExclude != null) {
                int iExcludeLen = sExclude.length;                    
                if (iExcludeLen != 0) {                               
                    for (int iIdx = 0; iIdx < iExcludeLen; iIdx++) {  
                        if (outVector.contains(sExclude [iIdx])) {    
                            outVector.remove(sExclude [iIdx]);        
                        }                                             
                    }                                                 
                }                                                     
            }                                                         
        } catch (SQLException sqlex) {
            throw new Exception (sqlex);
        }

        return (outVector);
    } /* End Method submitButton::selectIndexes::describeTable */    
    /**
     * 
     */
    public Vector describe () throws Exception 
    {
System.out.println ("{{{{{{{{{{{{{ WARNING: check that this describe is working OK, it was changed from the original with 2 arguments. }}}}}}}}}}}}}");            
        return Table.describe (connection, sDBName, sTableName, null);        
    }
    /**
     * 
     */
    public void drop () throws Exception 
    {
        MiscellaneaDB.dropTable(connection, sTableName);      
    }
    /**
     * Protected against SQL injection
     */
    static public void deleteRows (Connection connection, String sTableParam, String sWhere) throws Exception 
    {
        
        if (sTableParam == null)
            throw new Exception ("No table name provided.");
        if (sWhere == null)
            throw new Exception ("No where statement provided.");
        
        try {
            PreparedStatement pstmt = connection.prepareStatement("DELETE FROM " + sTableParam + " WHERE " + sWhere);
            pstmt.execute ();            
        } catch (SQLException sqlex) {
            throw new Exception (sqlex);
        }
        return;
    }
    /**
     * 
     */
    public void deleteRows (String sWhereCondition) throws Exception 
    {
        Table.deleteRows (connection, sTableName, sWhereCondition);
    }
    /**
     * Protected against SQL injection
     */
    public static ResultSet getQuery (Connection connectionParam, 
                                      String     sDBName, 
                                      String     sSelectColumn, 
                                      String     sFromTable) throws Exception 
    {
        ResultSet resultSet = null;
        String sQuery = "SELECT "    + sSelectColumn  +
                        " FROM "     + sFromTable     +
                        ";";

        try {
            Statement statement = connectionParam.createStatement();
            statement.execute ("USE " + sDBName + ";");
            PreparedStatement pstmt = connectionParam.prepareStatement (sQuery);
            resultSet = pstmt.executeQuery();
        }
        catch ( Exception sqlex ) {
            throw new Exception (sqlex); 
        }
        return resultSet;
    } /* End Method getQuery */
    /**
     * Protected against SQL injection
     */
    public static ResultSet getQuery (Connection connectionParam, 
                                      String     sDBName, 
                                      String     sSelectColumn, 
                                      String     sFromTable, 
                                      String     sWhereCondition, 
                                      String     sOrderBy) throws Exception
    {
        ResultSet resultSet = null;
        String sQuery = "SELECT "    + sSelectColumn   +
                        " FROM "     + sFromTable      +
                        " WHERE "    + sWhereCondition +
                        " ORDER BY " + sOrderBy +
                        ";";

        try {
            Statement statement = connectionParam.createStatement();
            statement.execute ("USE " + sDBName + ";");
            PreparedStatement pstmt = connectionParam.prepareStatement (sQuery);
            resultSet = pstmt.executeQuery();
        }
        catch ( Exception sqlex ) {
            throw new Exception (sqlex); 
        }
        return resultSet;
    } /* End Method getQuery */
    /**
     * Protected against SQL injection
     */
    public static ResultSet getQuery (Connection connectionParam, 
                                      String     sDBName, 
                                      String     sSelectColumn, 
                                      String     sFromTable, 
                                      String     sWhereCondition, 
                                      String     sOrderBy,
                                      String     sLimit) throws Exception
    {
        ResultSet resultSet = null;
        String sQuery = "SELECT "    + sSelectColumn   +
                        " FROM "     + sFromTable      +
                        " WHERE "    + sWhereCondition +
                        " ORDER BY " + sOrderBy +
                        " LIMIT "    + sLimit +
                        ";";

        try {
            Statement statement = connectionParam.createStatement();
            statement.execute ("USE " + sDBName + ";");
            PreparedStatement pstmt = connectionParam.prepareStatement (sQuery);
            resultSet = pstmt.executeQuery();
        }
        catch ( Exception sqlex ) {
            throw new Exception (sqlex); 
        }
        return resultSet;
    } /* End Method getQuery */
    /**
     * 
     */
    public ResultSet getQuery (String sColumnName) throws Exception 
    {
        return  Table.getQuery(connection, sDBName, sColumnName, sTableName);
    }
    /**
     * 
     */
    public ResultSet getQuery (String sColumnName, String sWhereCondition, String sOrderBy) throws Exception
    {
        return Table.getQuery(connection, sDBName, sColumnName, sTableName, sWhereCondition, sOrderBy);
    }
    /**
     *
     */
     public static void insert (Connection connectionParam,
                                    String     sDBase,
                                    String     sTable,
                                    Vector     vColumns,
                                    Vector     vValues)  throws Exception
    {
        Statement statement = null;
        
        if (connectionParam == null)
            throw new Exception ("No connection with the DB established yet.");

        if (sDBase == null || vColumns == null || vValues == null) {        
            throw new Exception ("Null values available for insert into the table.");
        }
        
        try {
            statement = connectionParam.createStatement();
            statement.execute ("USE " + sDBase + ";");

            int iSize = vColumns.size();
            if (iSize < 1)
                throw new Exception ("Error: Columns < 1.");
            
System.out.println (">>>>>>>>>>>>>>>> Table.insert");
            String sColumns = vColumns.get(0).toString();
            Object binValues  = vValues.get(0);
            for (int i = 1; i < iSize; i++) {
                sColumns   = sColumns  + ", " + vColumns.get(i).toString();
                binValues  = binValues + ", " + vValues.get(i);
            }
            String sSQLCommand = "INSERT INTO " + sTable + " (" + sColumns + ") VALUES (" + binValues + ");";
//System.out.println ("#" +  sSQLCommand);
            statement.execute (sSQLCommand);
        } 
        catch (SQLException ex) {
            throw new Exception (ex);
        }
        return;
    } /* end method writeTimeLine */
    /**
     * 
     */
    public void insert (Vector vColumnsParam, Vector vValues) throws Exception 
    {
        if (vColumnsParam == null)
            throw new Exception (" null vColumnParam.");
        if (vValues == null)
            throw new Exception (" null vValues.");
        
        int iColumnsParamLen = vColumnsParam.size();
        int iValuesLen = vValues.size();
        if (iColumnsParamLen != iValuesLen)
            throw new Exception ("Error: Columns size are different fron values size.");
        
        Vector vTempValues = new Vector ();
        for (int iIdx = 0; iIdx < iColumnsParamLen; iIdx++) {
            String sColumnParam = vColumnsParam.get(iIdx).toString();
//ACA 11/04/2012            if (!vColumns.contains(sColumnParam)) {
            if (vColumns != null) {
                if (!vColumns.contains(sColumnParam)) {
                    throw new Exception ("Error: Column " + sColumnParam + " not contained on vColumns");
                }
            }
//ACA 11/04/2012            vTempValues.add("'" + vValues.get(iIdx) + "'");
            vTempValues.add(vValues.get(iIdx));
        }
        
        Table.insert (connection, sDBName, sTableName, vColumnsParam, vTempValues);
    }
    /**
     *
     */
     public static void insertSingleRow (Connection connectionParam,
                                             String     sDBase,
                                             String     sTable,
                                             Vector     vColumns,
                                             Vector     vValues)  throws Exception
    {
        Statement statement = null;
        ResultSet resultSet = null;
        
        if (connectionParam == null)
            throw new Exception ("No connection with the DB established yet.");

        if (sDBase == null || vColumns == null || vValues == null) {        
            throw new Exception ("Null values available for insert into the table.");
        }
        
        try {
            statement = connectionParam.createStatement();
            statement.execute ("USE " + sDBase + ";");
            resultSet = statement.executeQuery("SELECT * FROM " + sTable + ";");
            resultSet.last ();
            int iRows = resultSet.getRow ();
            String sUpdates = null;

            if (iRows >= 1) {
                int iSize = vColumns.size();
                for (int i = 0; i < iSize; i++) {
                    String sColumn = vColumns.get(i).toString();
                    String sValue  = vValues.get(i).toString();
                    resultSet.getObject(sColumn);
                    boolean bTmp = resultSet.wasNull();
                    if (bTmp == false) {
                        throw new Exception ("Error: pre existing " + sColumn + "values in table " + sTable +".");
                    } else {
                        sUpdates = sUpdates + " " + sColumn + " = " + sValue + ",";
                    }
                }
                int iLastComa = sUpdates.lastIndexOf(',');
                sUpdates = sUpdates.substring(0, iLastComa -1);
                statement.execute ("UPDATE " + sTable + " SET " + sUpdates + ";");
                return;                
            } else {
                int iSize = vColumns.size();
                String sColumns = "";
                String sValues  = "";
                for (int i = 0; i < iSize; i++) {
                    sColumns = sColumns + ", " + vColumns.get(i).toString();
                    sValues  = sValues + ", " + vValues.get(i).toString();                    
                }
                sColumns = sColumns.substring(1);
                sValues  = sValues.substring(1);
                statement.execute ("INSERT INTO " + sTable + " (" + sColumns + ") VALUES (" + sValues + ");");                               
            }            
        } 
        catch (SQLException ex) {
            throw new Exception (ex);
        }
        return;
    } /* end method writeTimeLine */
    /**
     * 
     */
    public void insertSingleRow (Vector vColumnsParam, Vector vValues) throws Exception
    {
        if (vColumnsParam == null)
            throw new Exception (" null vColumnParam.");
        if (vValues == null)
            throw new Exception (" null vValues.");
        
        int iColumnsParamLen = vColumnsParam.size();
        int iValuesLen = vValues.size();
        if (iColumnsParamLen != iValuesLen)
            throw new Exception ("Error: Columns size are different fron values size.");
        
        Table.insertSingleRow (connection, sDBName, sTableName, vColumnsParam, vValues);
    }
    /**
     *
     * @param rs
     * @param vCurrentRowParam : this argument is necesary to allow this method to work on static context; to use it, just provide an unnamed new Vector ();
     * @param iColumnsShift
     * @return
     * @throws java.sql.SQLException
     * @throws java.lang.Exception
     */
    public static double [][] transferResultSet2Matrix (ResultSet rs, int iColumnsShift) throws SQLException, Exception
    {
        if (rs == null) {
            throw new Exception ("Null resultSet.");
        }

        rs.last();
        int iRow = rs.getRow();
        rs.first();

        if (iRow <= 0 ) {
            throw new Exception ("ResultSet contained no records" );
        }

        ResultSetMetaData rsmd = rs.getMetaData ();

        int iColumns = rsmd.getColumnCount();

        if (iRow <= 0 || iColumns <= 0)
            return null;

        Double DTemp;
        int iMatrixColLen = iColumns - iColumnsShift;
        double [][] dMatrix = new double [iRow][iMatrixColLen];

        for (int i = 0; i < iRow; i++) {
            Vector vCurrentRow = MiscellaneaDB.getCurrentRowFromResultSet (rs, iColumns);
            int iMtrxColCounter = 0;
            for (int j = iColumnsShift; j < iColumns; j++) {
                DTemp = Double.valueOf(vCurrentRow.get(j).toString());
                dMatrix [i][iMtrxColCounter] =  DTemp.doubleValue ();
 //               System.out.print (dMatrix [i][iMtrxColCounter] + " ");
                iMtrxColCounter++;
            }
//            System.out.println ();
            rs.next ();
//            vCurrentRowParam.removeAllElements();
        }

        return dMatrix;
    }
    public static Object [][] transferObjectResultSet2Matrix (ResultSet rs, int iColumnsShift) throws SQLException, Exception
    {
        if (rs == null) {
            throw new Exception ("Null resultSet.");
        }

        rs.last();
        int iRow = rs.getRow();
        rs.first();

        if (iRow <= 0 ) {
//            throw new Exception ("ResultSet contained no records" );
            return null;
        }

        ResultSetMetaData rsmd = rs.getMetaData ();

        int iColumns = rsmd.getColumnCount();

        if (iRow <= 0 || iColumns <= 0)
            return null;

        Object OTemp;
        int iMatrixColLen = iColumns - iColumnsShift;
        Object [][] OMatrix = new Object [iRow][iMatrixColLen];

        for (int i = 0; i < iRow; i++) {
            Vector vCurrentRow = MiscellaneaDB.getCurrentRowFromResultSet (rs, iColumns);
            int iMtrxColCounter = 0;
            for (int j = iColumnsShift; j < iColumns; j++) {
                OTemp = vCurrentRow.get(j);
                OMatrix [i][iMtrxColCounter] =  OTemp;
 //               System.out.print (dMatrix [i][iMtrxColCounter] + " ");
                iMtrxColCounter++;
            }
//            System.out.println ();
            rs.next ();
//            vCurrentRowParam.removeAllElements();
        }

        return OMatrix;
    }
} /* end class Table */
